package com.symc.sims0213xfw.dao.impl;

import com.symc.sims0213xfw.bean.User;
import com.symc.sims0213xfw.dao.UserDao;
import com.symc.sims0213xfw.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author: 凤文  沈阳医学院2019级医学信息工程 0213
 * @CreateTime: 2022/01/14 11:26
 * @Description: 实现JD功能 CURD
 */
public class UserDaoImpl implements UserDao {

    private static QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public void getUserNameAndPassword() throws SQLException {
        String sql = "select * from user";
        List<User> users = runner.query(sql,
                new BeanListHandler<>(User.class));
        System.out.println(users.size());
        for (User user : users) {
            System.out.println(user.getUname() + " " + user.getUpassword());
        }
    }

    @Override
    public void insertRecord() {
        String sql = "insert into user values('凤文','password')";
        try {
            int i = runner.update(sql);
            if (i > 0) {
                System.out.println("插入成功！");
            } else {
                System.out.println("插入失败！");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public int insertUser(String uname, String upassword) throws SQLException {
        String sql = "insert into user values(?,?)";
        int i = runner.update(sql, new Object[]{
                uname, upassword
        });
        return i;
    }

    @Override
    public User getUser(String uname) {
        String sql = "select * from user where uname='" + uname + "'";
        User user = null;
        try {
            user = runner.query(sql, new BeanHandler<>(User.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return user;
    }

    public boolean queryUserPrimaryKey(String uname) {
        boolean isConflictWithPrimaryKey = false;
        User result = null;
        try {
            result = runner.query("select * from user where uname=?",
                    new BeanHandler<>(User.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (result != null) {
            isConflictWithPrimaryKey = true;
        }
        return isConflictWithPrimaryKey;
    }

    /**
     * 把表中姓名为 fengwen 的记录的密码 改为 123456
     */
    @Override
    public void updateData(String name, String password) throws SQLException {

        int i = runner.update(
                "UPDATE user SET upassword=? WHERE uname=?",
                new Object[]{password, name});
        if (i > 0) {
            System.out.println("成功修改" + i + "条数据");
        } else {
            System.out.println("修改失败！");
        }
    }

}
